package com.starchen.optimalselection.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.starchen.optimalselection.admin.mapper.AdminMenuMapper;
import com.starchen.optimalselection.admin.model.AdminMenu;
import com.starchen.optimalselection.admin.model.vo.AdminMenuVo;
import com.starchen.optimalselection.admin.model.vo.RouterVo;
import com.starchen.optimalselection.admin.service.AdminMenuService;
import com.starchen.optimalselection.utils.RouterHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author daxilong
 * @date 2025/3/21 21:24
 */
@Service
public class AdminMenuServiceImpl extends ServiceImpl<AdminMenuMapper, AdminMenu> implements AdminMenuService {


    //菜单列表（树形）
    @Override
    public List<AdminMenu> findNodes() {
        //获取所有菜单
        List<AdminMenu> sysMenuList = baseMapper.selectList(null);
        List<AdminMenu> list = sysMenuList.stream().filter(item -> item.getParentId() == 0).map(item -> {
            item.setChildren(getChildrens(item,sysMenuList));
            return item;
        }).collect(Collectors.toList());
        return list;
    }

    /**
     * 递归每个菜单的所有子菜单
     */
    private List<AdminMenu> getChildrens(AdminMenu root,List<AdminMenu> all){
        List<AdminMenu> children = all.stream().filter(item ->
                item.getParentId() == root.getId()).map(item -> {
            item.setChildren(getChildrens(item,all));
            return item;
        }).collect(Collectors.toList());
        return children;
    }

    //删除菜单
    @Override
    public boolean removeMenuById(Long id) {
        //查询当前删除菜单下面是否子菜单
        //根据id = parentid
        QueryWrapper<AdminMenu> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",id);
        Long count = baseMapper.selectCount(wrapper);
        if(count > 0) {//有子菜单
            return false;
        }
        //调用删除
        baseMapper.deleteById(id);
        return true;
    }

    //查询用户可以操作菜单
    @Override
    public List<RouterVo> findMenusByUserId(Integer id) {

        //admin是超级管理员，操作所有内容
        List<AdminMenu> sysMenuList;
        //判断userid值是1代表超级管理员，查询所有权限数据
        if(id == 1) {
            QueryWrapper<AdminMenu> wrapper = new QueryWrapper<>();
            wrapper.eq("status",1);
            //wrapper.orderByAsc("sort_value");
            sysMenuList = baseMapper.selectList(wrapper);
        } else {
            sysMenuList = new ArrayList<>();
            //如果userid不是1，其他类型用户，查询这个用户权限
//            QueryWrapper<AdminMenu> wrapper = new QueryWrapper<>();
//            wrapper.eq("status",1);
//            wrapper.eq("id",id);
//            sysMenuList = baseMapper.selectList(wrapper);
            //Admin
        }

        //构建是树形结构
        List<AdminMenu> sysMenuTreeList = sysMenuList.stream().filter(item -> item.getParentId() == 0).map(item -> {
            item.setChildren(getChildrens(item,sysMenuList));
            return item;
        }).collect(Collectors.toList());

        //转换成前端路由要求格式数据
        List<RouterVo> routerVoList = RouterHelper.buildRouters(sysMenuTreeList);
        return routerVoList;
    }

    @Override
    public List<String> getUserButtonList(Integer userId) {
        List<AdminMenu> sysMenuList = null;
        //判断是否管理员
        if("1".equals(userId)) {
            sysMenuList =
                    baseMapper.selectList(new QueryWrapper<AdminMenu>().eq("status",1));
        } else {
            //sysMenuList = this.findMenusByUserId(userId);
        }
        //sysMenuList遍历
        List<String> permissionList = new ArrayList<>();
        for (AdminMenu sysMenu:sysMenuList) {
            // type=2
            if(sysMenu.getType()==2) {
                String perms = sysMenu.getPerms();
                permissionList.add(perms);
            }
        }
        return permissionList;
    }

    // 将List<SysMenu>对象转换成List<SysMenuVo>对象
    private List<AdminMenuVo> buildMenus(List<AdminMenu> menus) {

        List<AdminMenuVo> sysMenuVoList = new LinkedList<AdminMenuVo>();
        for (AdminMenu sysMenu : menus) {
            AdminMenuVo sysMenuVo = new AdminMenuVo();
            //sysMenuVo.setTitle(sysMenu.getTitle());
            sysMenuVo.setName(sysMenu.getComponent());
            List<AdminMenu> children = sysMenu.getChildren();
            if (!CollectionUtils.isEmpty(children)) {
                sysMenuVo.setChildren(buildMenus(children));
            }
            sysMenuVoList.add(sysMenuVo);
        }
        return sysMenuVoList;
    }

}
